import { _decorator, Component, Node, Vec3, Label, UITransform, Color, Sprite, Input, EventTouch, input, instantiate, Vec2 } from 'cc';
import CCUtils from '../util/CCUtils';
import { CardItem } from './CardItem';
import { allColumn, allRow, CardType, cellHeight, cellWidth, gameConst, LayerInfo } from './GameConst';
import GImage from './GImage';
import { PosInfo } from './PosInfo';
const { ccclass, property } = _decorator;

@ccclass('LayerItem')
export class LayerItem extends Component {


    public bg:GImage = null;
    private content:Node = null;
    private waitContent:Node = null;
    private content_UITransform:UITransform = null;
    private waitContent_UITransform:UITransform = null;

    private static baseLayarId:number = 1;

    private allWidth:number = 0;
    private allHeight:number = 0;

    private beginX:number = 0;
    private beginY:number = 0;

    public info:LayerInfo = null;

    onLoad(){
        this.bg = CCUtils.getGImage(this.node,"bg");
        this.content = CCUtils.findChild(this.node,"content");
        this.waitContent = CCUtils.findChild(this.node,"waitContent");
        this.content_UITransform = this.content.getComponent(UITransform);
        this.waitContent_UITransform = this.waitContent.getComponent(UITransform);

        // this.allWidth = this.content_UITransform.width; //要格子宽的整数倍
        // this.allHeight = this.content_UITransform.height;//要格子高的整数倍
        // this.beginX = -this.content_UITransform.width/2;
        // this.beginY = this.content_UITransform.height/2;

        this.allWidth = cellWidth * allColumn;
        this.allHeight = cellHeight * allRow;
        this.beginX = -this.allWidth/2;
        this.beginY = this.allHeight/2;

        //目前是：总宽810，总高900，格子宽35，格子高40,列数18，行数18
        console.log(`初始化地图信息，总宽${this.allWidth}，总高${this.allHeight}，格子宽${cellWidth}，格子高${cellHeight},列数${allColumn}，行数${allRow}`)

    }


    /**
     * 初始化卡片
     * @param type 
     * @param pos 
     */
    public init() {
        this.info = {layerId:LayerItem.baseLayarId, allCards:new Map<string, CardItem>()};
        LayerItem.baseLayarId ++;

        let pixelX = (this.info.layerId%10)*3; //不同layer的层偏移量，好看一点，不会完全覆盖
        let pixelY =  - (this.info.layerId%10)*3; //不同layer的层偏移量，好看一点，不会完全覆盖
        this.node.setPosition(pixelX, pixelY); 
        
        this.bg.loadSpriteFrame(`ui/bg${this.info.layerId%10}/spriteFrame`);
    }

    /**
     * 添加一个卡牌到待拖放区域
     * @param type 卡牌类型
     * @param column 列,横坐标
     * @param row 行 纵坐标
     */
    public addNewCardToWaitContent(type:CardType,column?:number,row?:number) {

        let card:Node = instantiate(gameConst.globelPrefab.cardPrefab);
        let citem:CardItem = card.getComponent(CardItem);
        this.waitContent.addChild(card);
        // this.content.addChild(card);
        card.active = true;
        citem.init(this,type,null);

        card.on(Input.EventType.TOUCH_START, this.onTouchStartCard, this);
        card.on(Input.EventType.TOUCH_MOVE, this.onTouchMoveCard, this);
        card.on(Input.EventType.TOUCH_END, this.onTouchEndCard, this);

    }

     /**
     * 移除卡片
     * @param card 
     */
     public removeCard(card:CardItem) {
        console.log("删除的item",`${card.pos.gridX}_${card.pos.gridY}`);
        this.info.allCards.delete(`${card.pos.gridX}_${card.pos.gridY}`);
        card.node.removeFromParent();
        card.destroy();
        console.log("当前的数据是", this.info.allCards);
    }


    private onTouchStartCard(e:EventTouch) {
        let card:Node = e.currentTarget;
        // let cardTans:UITransform = card.getComponent(UITransform);
        let cardWorldPoin:Vec3 = null;
        if (card.parent == this.waitContent) {
            cardWorldPoin = this.waitContent_UITransform.convertToWorldSpaceAR(new Vec3(card.getPosition().x, card.getPosition().y));
        }else{
            cardWorldPoin = this.content_UITransform.convertToWorldSpaceAR(new Vec3(card.getPosition().x, card.getPosition().y));
        }
        let cardLocalPoin = this.content_UITransform.convertToNodeSpaceAR(cardWorldPoin);
        card.removeFromParent();
        this.content.addChild(card);
        card.setPosition(cardLocalPoin);
    }

    private onTouchMoveCard(e:EventTouch) {
        let card:Node = e.currentTarget;
        let item:CardItem = card.getComponent(CardItem);

        let pos:PosInfo = this.transPointByWorldPoint(e.getUILocation());


        item.changeRedMask(this.thisPosOverlapForOneLayer(pos.gridX,pos.gridY));

        card.setPosition(pos.pixelX, pos.pixelY);
    }

    private onTouchEndCard(e:EventTouch) {

        let card:Node = e.currentTarget;
        let item:CardItem = card.getComponent(CardItem);
        // let cardTans:UITransform = card.getComponent(UITransform);
        let pos:PosInfo = this.transPointByWorldPoint(e.getUILocation());
        let isCover:boolean = this.thisPosOverlapForOneLayer(pos.gridX,pos.gridY);
        if (isCover) {
            item.changeRedMask(false);
            if (item.pos != null) { //放回去本来的位置
                card.setPosition(item.pos.pixelX, item.pos.pixelY);
            }else{ //放回去待拖放区域
                card.removeFromParent();
                card.setPosition(0,0);
                this.waitContent.addChild(card);
            }
        }else{

            if (this.isOutSide(pos.gridX,pos.gridY)) { //超出可放置范围了，看看要不要删了
                if (item.pos != null) { //本来有位置，直接删了
                    this.removeCard(item);
                }else{//放回去待拖放区域
                    card.removeFromParent();
                    card.setPosition(0,0);
                    this.waitContent.addChild(card);
                }
                
            }else{
                if (item.pos != null) { //本来有位置，先删掉旧数据，再更新位置
                    this.info.allCards.delete(`${item.pos.gridX}_${item.pos.gridY}`);
                }
                this.info.allCards.set(`${pos.gridX}_${pos.gridY}`, item);
                item.setPos(pos);
            }
           
        }

        console.log("现在的层数据是：",this.info.allCards);
    }


    /**
     * 将世界坐标转换成对应content容器的格子坐标
     * @param worldPoint 
     * @returns 
     */
    private transPointByWorldPoint(worldPoint:Vec2):PosInfo {

        let pos:Vec3 = this.content_UITransform.convertToNodeSpaceAR(new Vec3(worldPoint.x,worldPoint.y));
        // console.log("移动的位置", e.getUILocation().x, e.getUILocation().y, pos.x, pos.y);

        let endGridX:number = (pos.x - this.beginX)/cellWidth - 1;
        let endGridY:number = (this.beginY - pos.y)/cellHeight - 1;

        endGridX = Math.ceil(endGridX);
        endGridY = Math.ceil(endGridY);

        // endGridX = Math.max(endGridX,0);
        // endGridX = Math.min(endGridX,allColumn-2);
        // endGridY = Math.max(endGridY,0);
        // endGridY = Math.min(endGridY,allRow-2);

        let endPixelX:number = this.beginX + endGridX * cellWidth + cellWidth; //最后这个是卡牌的半个宽度
        let endPixelY:number = this.beginY - (endGridY * cellHeight) - cellHeight;


        let info:PosInfo = new PosInfo();
        info.gridX = endGridX;
        info.gridY = endGridY;
        info.pixelX = endPixelX;
        info.pixelY = endPixelY;

        return info;
        
    }


     /**
     * 这个位置是否重叠了其他卡牌，针对同一层
     * true 为重叠了，false为没重叠
     */
    private thisPosOverlapForOneLayer(gridX:number, gridY:number):boolean {
        let beginX:number = Math.max(gridX - 1, 0); 
        let beginY:number = Math.max(gridY - 1, 0); 
        let endX:number = Math.min(gridX + 1, allColumn-1); 
        let endY:number = Math.min(gridY + 1, allColumn-1); 
        for (let x:number = beginX; x <= endX; x++) {
            for (let y:number = beginY; y <= endY; y++) {
                if (this.info.allCards.get(`${x}_${y}`) != null){
                    return true;
                }
            }
        }
        // console.log(`找到一个位置${gridX}_${gridY},判断范围${beginX}_${beginY}---${endX}_${endY}`);
        return false;
    }


    /**
     * 是否已经超出可放置的范围,true就是超出了
     * @param gridX 
     * @param gridY 
     * @returns 
     */
    private isOutSide(gridX:number, gridY:number):boolean {
        if (gridX<0 || gridX > allColumn-2) {
            return true;
        }
        if (gridY<0 || gridY > allRow-2) {
            return true;
        }
        return false;
    }



    /**
     * 获取所有卡牌的设置
     */
    public getAllInfo():any {
        let resule:any = {layerId:this.info.layerId,cards:[]};
        this.info.allCards.forEach((item:CardItem,key:string)=>{
            let onCard:any = {type:item.type,gridX:item.pos.gridX, gridY:item.pos.gridY};
            resule.cards.push(onCard);
        })
        return resule;
    }
    
}


